<template>
  <div class="xtx-numbox">
    <div class="label" v-if="isShowLabel">数量</div>
    <div class="numbox">
      <a @click="sub" href="javascript:;">-</a>
      <input type="text" readonly :value="num" />
      <a @click="add" href="javascript:;">+</a>
    </div>
  </div>
</template>
<script>
import { ref, watch } from 'vue'
export default {
  props: {
    isShowLabel: {
      type: Boolean,
      default: true
    },
    // 接收双向绑定的变量
    modelValue: {
      type: Number,
      default: 1
    },
    min: {
      type: Number,
      default: 1
    },
    max: {
      type: Number,
      default: 10
    }
  },
  name: 'XtxNumbox',
  emit: ['update:modelValue'],
  setup (props, { emit }) {
    const num = ref(1)
    // 减减
    const sub = () => {
      if (props.min === num.value) return
      num.value--
      // 1.同步num的值到v-model绑定变量（子-父）
      emit('update:modelValue', num.value)
    }
    // 加加
    const add = () => {
      if (props.max === num.value) return
      num.value++
      // 1.同步num的值到v-model绑定变量（子-父）
      emit('update:modelValue', num.value)
    }
    // 把v-modal 绑定变量值同步给num(父-子)
    watch(() => props.modelValue, (newVal) => {
      num.value = newVal
    }, {
      immediate: true // 默认同步一次
    })
    return { num, sub, add }
  }
}
</script>
<style scoped lang="less">
.xtx-numbox {
  display: flex;
  align-items: center;
  .label {
    width: 60px;
    color: #999;
    padding-left: 10px;
  }
  .numbox {
    width: 120px;
    height: 30px;
    border: 1px solid #e4e4e4;
    display: flex;
    > a {
      width: 29px;
      line-height: 28px;
      text-align: center;
      background: #f8f8f8;
      font-size: 16px;
      color: #666;
      &:first-of-type {
        border-right: 1px solid #e4e4e4;
      }
      &:last-of-type {
        border-left: 1px solid #e4e4e4;
      }
    }
    > input {
      width: 60px;
      padding: 0 5px;
      text-align: center;
      color: #666;
    }
  }
}
</style>
